package com.kmstech.greeting.cli;

import java.util.List;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingException;

import com.kmstech.greeting.entities.Greeting;
import com.kmstech.greeting.services.GreetingService;

public class GreetingCli {

  public static void main(String[] args) throws Exception {
    Context jndiContext = getInitialContext();
    GreetingService greetingService = (GreetingService) jndiContext
        .lookup("greeting/GreetingBean/remote");

    String command;
    do {
      command = Console.readLine("[add, list, exit]> ");

      if ("add".equals(command)) {
        String language = Console.readLine("language> ");
        String message = Console.readLine(" message> ");
        greetingService.addGreeting(language, message);
        System.out.println("new Greeting added.");
      }
      else if ("list".equals(command)) {
        List<Greeting> greetings = greetingService.getGreetings();
        for (Greeting greeting : greetings) {
          System.out.printf("%s | %s\n", greeting.getLanguage(),
              greeting.getMessage());
        }
      }
    }
    while (!"exit".equals(command));
  }

  private static Context getInitialContext() throws NamingException {
    Properties p = new Properties();
    p.put(Context.INITIAL_CONTEXT_FACTORY,
        "org.jnp.interfaces.NamingContextFactory");
    p.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
    p.put(Context.PROVIDER_URL, "jnp://localhost:1099");
    return new javax.naming.InitialContext(p);
  }
}
